package org.squabble.service;

import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.squabble.dao.TagDAO;
import org.squabble.domain.Tag;

@Service
public class TagService {

	@Autowired
	TagDAO tagDAO;

	public Tag getTag(String name) {
		return tagDAO.getTag(name);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public Tag createTag(String name) {
		Tag tag = new Tag();
		tag.setName(name);
		tag = tagDAO.save(tag);
		return tag;
	}

	public Set<Tag> saveTags(String tags) {
		return saveTags(tags, new HashSet<Tag>());
	}

	public Set<Tag> saveTags(String tags, Set<Tag> tagSet) {
		StringTokenizer st = new StringTokenizer(tags);
		tagSet.clear();
		while (st.hasMoreTokens()) {
			String tagname = st.nextToken();
			if (tagname.length() >= 3) {
				Tag tag = getTag(tagname);
				if (tag == null) {
					tag = createTag(tagname);
				}
				tagSet.add(tag);
			}
		}
		return tagSet;
	}

}
